package com.huitone.gddw.service.impl.monitoring;


import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


import org.springframework.stereotype.Service;



import com.huitone.gddw.dao.entity.AlarmReceiveUser;


import com.huitone.gddw.dao.entity.ObjItem;
import com.huitone.gddw.dao.entity.ObjItemProperty;
import com.huitone.gddw.dao.entity.ObjectManagement;
import com.huitone.gddw.dao.entity.Pid;
import com.huitone.gddw.dao.entity.ReturnedValue;

import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.monitoring.ObjectItemDao;
import com.huitone.gddw.service.SystemMonitoringService;
import com.huitone.gddw.utils.MonitoringResult;
import com.huitone.gddw.utils.MonitoringUtils;
import com.huitone.gddw.utils.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 保存、查找系统监控数据service实现类
 * @author lipengfei
 *
 */
@Service("sysService")
public class SystemMonitoringServiceImpl implements SystemMonitoringService {
	@Resource
	ObjectItemDao objDao;
	
	@Override
	public MonitoringResult<Map<String, Object>> loadSysInformation() {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//传送数据的map		
		Map<String, String> map = new HashMap<>();
		map.put("objType","host");
		//用于存放结果的map集合
		Map<String, Object> listMap = new HashMap<>();
		List<ObjectManagement> hostNameList = objDao.selectObjName(map);
		ObjectManagement obj = hostNameList.get(0);
		List<Map<String, String>> basicList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> hardwareList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> taskList = new ArrayList<Map<String, String>>();
		
		if(obj!=null){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "basic");
				ObjItem basicItem = objDao.selectObjItemByItemName(objmap);
				if(basicItem!=null){
					basicList = objDao.selectCnValue(basicItem.getItemId());
				}
				objmap.put("itemName", "hardware");
				ObjItem hardwareItem = objDao.selectObjItemByItemName(objmap);
				if(hardwareItem!=null){	
					hardwareList = objDao.selectCnValue(hardwareItem.getItemId());
					
				}
				objmap.put("itemName", "task");
				ObjItem taskItem = objDao.selectObjItemByItemName(objmap);
				if(taskItem!=null){
					taskList = objDao.selectCnValue(taskItem.getItemId());
				}
				objmap.put("itemName", "recuse");
				ObjItem recuseItem = objDao.selectObjItemByItemName(objmap);
				
				Calendar cal =Calendar.getInstance();
				cal.add(Calendar.DAY_OF_MONTH, -1);
				Date date =cal.getTime();
				
				List<String> iowaitList =getHistorySystemInformation( recuseItem.getItemId(), "iowait",date);
				
				List<String> cpusysList =getHistorySystemInformation(recuseItem.getItemId(), "cpusys",date);
				
				List<String> cpuuserList =getHistorySystemInformation(recuseItem.getItemId(), "cpuuser",date);
				
				List<Integer> cpuClockList = getHistoryClock(recuseItem.getItemId(), "cpuuser", date);
				
				List<String> memuseList =getHistorySystemInformation(recuseItem.getItemId(), "memuse",date);
				
				List<String> swapuseList =getHistorySystemInformation(recuseItem.getItemId(), "swapuse",date);
				
				List<Integer> memClockList = getHistoryClock(recuseItem.getItemId(), "swapuse", date);
				
				List<String> cpuloadList =getHistorySystemInformation(recuseItem.getItemId(), "cpuload",date);
				
				List<Integer> loadClockList = getHistoryClock(recuseItem.getItemId(), "cpuload", date);
				
				List<String> diskList =getHistorySystemInformation(recuseItem.getItemId(), "disk",date);
				
				List<Integer> diskClockList = getHistoryClock(recuseItem.getItemId(), "disk", date);
				
				List<String> recvList =getHistorySystemInformation(recuseItem.getItemId(), "recv",date);
				
				List<String> sendList =getHistorySystemInformation(recuseItem.getItemId(), "send",date);
				
				List<Integer> recvClockList = getHistoryClock(recuseItem.getItemId(), "send", date);
				
				map.put("itemType", "pid");
				List<Pid> pidList = getPid(objmap);
				listMap.put("hostName", hostNameList);
				listMap.put("basic", basicList);
				listMap.put("hardware", hardwareList);
				listMap.put("task", taskList);
				listMap.put("iowait", iowaitList);
				listMap.put("cpusys", cpusysList);
				listMap.put("cpuuser", cpuuserList);
				listMap.put("cpuclock", cpuClockList);
				listMap.put("memuse", memuseList);
				listMap.put("swapuse", swapuseList);
				listMap.put("memclock", memClockList);
				listMap.put("cpuload", cpuloadList);
				listMap.put("loadclock", loadClockList);
				listMap.put("disk", diskList);
				listMap.put("diskclock", diskClockList);
				listMap.put("recv", recvList);
				listMap.put("send", sendList);
				listMap.put("recvclock", recvClockList);
				listMap.put("pid", pidList);
			//对数据结果进行包装传送
			result.setStatus(0);
			result.setMsg("主机监控信息加载成功");
			result.setData(listMap);
			return result;
	}else{
		MonitoringUtils.MonitoringException("没有主机对象");
	}
	//对数据结果进行包装传送
	result.setStatus(0);
	result.setMsg("主机监控信息加载成功");
	listMap.put("hostName", hostNameList);
	result.setData(listMap);
	return result;
}
	
	public List<String> getHistorySystemInformation(String itemId,String name,Date date) {
		Map<String, Object> map = new HashMap<>();
		map.put("itemId", itemId);
		map.put("keyName", name);
		map.put("startTime", date.getTime()/1000);
		map.put("endTime", new Date().getTime()/1000);
		System.out.println(date.getTime()/1000);
		List<String> list = objDao.selectHistoryValue(map);
		return list;
	}
	public List<Integer> getHistoryClock(String itemId,String name,Date date) {
		Map<String, Object> map = new HashMap<>();
		map.put("itemId", itemId);
		map.put("keyName", name);
		map.put("startTime", date.getTime()/1000);
		map.put("endTime", new Date().getTime()/1000);
		
		System.out.println(date.getTime()/1000);
		List<Integer> list = objDao.selectHistoryClock(map);
		return list;
	}
	public List<Pid> getPid(Map<String, String> objmap){
		List<ObjItem> pidItems = objDao.selectObjItemByType(objmap);
		System.out.println(pidItems);
		List<Pid> pidList = new ArrayList<Pid>();
		if(!pidItems.isEmpty()){
			for(ObjItem pidItem:pidItems){
				List<Map<String, String>> pidItemList = objDao.selectValue(pidItem.getItemId());
				Pid pid = new Pid();
				if(!pidItemList.isEmpty()){
					for (Map<String, String> item:pidItemList) {
						if(item.get("KEY").equals("piduser")){
							pid.setPidUser(item.get("VALUE"));
						}else if(item.get("KEY").equals("pidcpu")){
							pid.setPidCpu(item.get("VALUE"));
						}else if(item.get("KEY").equals("pidmem")){
							pid.setPidMem(item.get("VALUE"));
						}else if(item.get("KEY").equals("starttime")){
							pid.setStarttime(item.get("VALUE"));
						}else if(item.get("KEY").equals("stutas")){
							pid.setStutas(item.get("VALUE"));
						}else if(item.get("KEY").equals("pidcount")){
							pid.setNowTaskCount(item.get("VALUE"));
						}
					}
				}
				pid.setPidName(pidItem.getItemName());
				Map<String, String> map = new HashMap<>();
				map.put("itemId",pidItem.getItemId());
				ObjItemProperty pro = new ObjItemProperty();
				pro.setKeyName("pidcount");
				pro.setItemId(pidItem.getItemId());
				if(objDao.selectKeyIdByItemId(pro)!=null){
					map.put("keyId", objDao.selectKeyIdByItemId(pro));
					if(objDao.selectAlarm(map)!=null){
						pid.setMinTaskCount(objDao.selectAlarm(map).getLowerLimit());
						pid.setMaxTaskCount(objDao.selectAlarm(map).getUpperLimit());
					}
				}
				pid.setRemark(pidItem.getRemark());
				AlarmReceiveUser user = objDao.getAlarmReceiveUser(objmap);
				if(user!=null){
					pid.setAlarmRec(user.getReceiveUser());
					pid.setPhone(user.getPhone());
				}
				pidList.add(pid);
			}
		}
		return pidList;
	}
	public List<String> getClockList(List<Integer> clockList){
		List<String> list = new ArrayList<String>();
		for(Integer clock:clockList){		
			Calendar calen = Calendar.getInstance();
			Date time = new Date(clock*1000L);
			System.out.println(time);
			calen.setTime(time);
			list.add(MonitoringUtils.getTimeByCalendar(calen));
		}
		System.out.println(list);
		return list;
	}
	
	
	@Override
	public MonitoringResult<Map<String, Object>> loadSysInformationByHost(ReturnedValue value) {
		//用于传递数据结果的方法
				MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
				//传送数据的map		
				Map<String, String> map = new HashMap<>();
				map.put("objId", value.getHostId());
				//用于存放结果的map集合
				Map<String, Object> listMap = new HashMap<>();
				List<Map<String, String>> basicList = new ArrayList<Map<String, String>>();
				List<Map<String, String>> hardwareList = new ArrayList<Map<String, String>>();
				List<Map<String, String>> taskList = new ArrayList<Map<String, String>>();
				
				//用于存放参数的map集合
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", value.getHostId());
				objmap.put("itemName", "basic");
				ObjItem basicItem = objDao.selectObjItemByItemName(objmap);
				if(basicItem!=null){
					basicList = objDao.selectCnValue(basicItem.getItemId());
				}
				objmap.put("itemName", "hardware");
				ObjItem hardwareItem = objDao.selectObjItemByItemName(objmap);
				if(hardwareItem!=null){	
					hardwareList = objDao.selectCnValue(hardwareItem.getItemId());
					
				}
				objmap.put("itemName", "task");
				ObjItem taskItem = objDao.selectObjItemByItemName(objmap);
				if(taskItem!=null){
					taskList = objDao.selectCnValue(taskItem.getItemId());
				}
				objmap.put("itemName", "recuse");
				ObjItem recuseItem = objDao.selectObjItemByItemName(objmap);
						
				Calendar cal =Calendar.getInstance();
				System.out.println(cal.getTime());
				cal.add(Calendar.DAY_OF_MONTH, -1);
				Date date =cal.getTime();
				System.out.println(date);
				if(recuseItem!=null){
					List<String> iowaitList =getHistorySystemInformation( recuseItem.getItemId(), "iowait",date);
					
					List<String> cpusysList =getHistorySystemInformation(recuseItem.getItemId(), "cpusys",date);
							
					List<String> cpuuserList =getHistorySystemInformation(recuseItem.getItemId(), "cpuuser",date);
							
					List<Integer> cpuClock= getHistoryClock(recuseItem.getItemId(), "cpuuser", date);
					System.out.println(cpuClock);
					List<String> cpuClockList = getClockList(cpuClock);
					
					List<String> memuseList =getHistorySystemInformation(recuseItem.getItemId(), "memuse",date);
							
					List<String> swapuseList =getHistorySystemInformation(recuseItem.getItemId(), "swapuse",date);
							
					List<Integer> memClock = getHistoryClock(recuseItem.getItemId(), "swapuse", date);
					
					List<String> memClockList = getClockList(memClock);
					
					List<String> cpuloadList =getHistorySystemInformation(recuseItem.getItemId(), "cpuload",date);
							
					List<Integer> loadClock = getHistoryClock(recuseItem.getItemId(), "cpuload", date);
							
					List<String> loadClockList = getClockList(loadClock);
					
					List<String> diskList =getHistorySystemInformation(recuseItem.getItemId(), "disk",date);
							
					List<Integer> diskClock = getHistoryClock(recuseItem.getItemId(), "disk", date);
							
					List<String> diskClockList = getClockList(diskClock);
					
					List<String> recvList =getHistorySystemInformation(recuseItem.getItemId(), "recv",date);
							
					List<String> sendList =getHistorySystemInformation(recuseItem.getItemId(), "send",date);
							
					List<Integer> sendClock = getHistoryClock(recuseItem.getItemId(), "send", date);
					
					System.out.println(sendClock);
					List<String> recvClockList = getClockList(sendClock);
					listMap.put("basic", basicList);
					listMap.put("hardware", hardwareList);
					listMap.put("task", taskList);
					
					listMap.put("iowait", iowaitList);
					listMap.put("cpusys", cpusysList);
					listMap.put("cpuuser", cpuuserList);
					listMap.put("cpuclock", cpuClockList);
					listMap.put("memuse", memuseList);
					listMap.put("swapuse", swapuseList);
					listMap.put("memclock", memClockList);
					listMap.put("cpuload", cpuloadList);
					listMap.put("loadclock", loadClockList);
					listMap.put("disk", diskList);
					listMap.put("diskclock", diskClockList);
					listMap.put("recv", recvList);
					listMap.put("send", sendList);
					listMap.put("recvclock", recvClockList);
					
				}
				map.put("itemType", "pid");
				List<Pid> pidList = getPid(objmap);
				listMap.put("pid", pidList);
				
			//对数据结果进行包装传送
			result.setStatus(0);
			result.setMsg("主机监控信息加载成功");
			//对数据结果进行包装传送
			result.setData(listMap);
			return result;
		
	}

	@Override
	public MonitoringResult<Map<String, Object>> loadPidInformation() {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//传送数据的map		
		Map<String, String> map = new HashMap<>();
		map.put("objType","host");
		//用于存放结果的map集合
		Map<String, Object> listMap = new HashMap<>();
		List<ObjectManagement> hostNameList = objDao.selectObjName(map);
		List<Map<String, String>> basicList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> hardwareList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> taskList = new ArrayList<Map<String, String>>();
		
		if(!hostNameList.isEmpty()){
			ObjectManagement obj = hostNameList.get(0);
			System.out.println(obj);
			if(obj!=null){	
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "basic");
				ObjItem basicItem = objDao.selectObjItemByItemName(objmap);
				if(basicItem!=null){
					basicList = objDao.selectCnValue(basicItem.getItemId());
				}
				
				objmap.put("itemName", "hardware");
				ObjItem hardwareItem = objDao.selectObjItemByItemName(objmap);
				if(hardwareItem!=null){
					hardwareList = objDao.selectCnValue(hardwareItem.getItemId());
				}
				objmap.put("itemName", "task");
				ObjItem taskItem = objDao.selectObjItemByItemName(objmap);
				if(taskItem!=null){
					taskList = objDao.selectCnValue(taskItem.getItemId());
				}
				
				objmap.put("itemType", "pid");
				List<Pid> pidList = getPid(objmap);
				listMap.put("hostName", hostNameList);
				listMap.put("basic", basicList);
				listMap.put("hardware", hardwareList);
				listMap.put("task", taskList);
				listMap.put("pid", pidList);
			//对数据结果进行包装传送
			result.setStatus(0);
			result.setMsg("主机监控信息加载成功");
			}else{
				result.setMsg("没有加载到该进程的指标");
			}
		
		}else{
			result.setMsg("没有加载进程信息");
		}
				
		result.setData(listMap);
		return result;
		
	}

	@Override
	public MonitoringResult<Map<String, Object>> loadPidInformationByHost(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
//		//传送数据的map		
//		Map<String, String> map = new HashMap<>();
//		map.put("objId", value.getHostId());
		//用于存放结果的map集合
		Map<String, Object> listMap = new HashMap<>();
		ObjectManagement obj = objDao.selectObjById(value.getHostId());
		List<Map<String, String>> basicList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> hardwareList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> taskList = new ArrayList<Map<String, String>>();
		if(obj!=null){	
			Map<String, String> objmap = new HashMap<>();
			objmap.put("objId", obj.getObjId());
			objmap.put("itemName", "basic");
			ObjItem basicItem = objDao.selectObjItemByItemName(objmap);
			if(basicItem!=null){
				basicList = objDao.selectCnValue(basicItem.getItemId());
			}
			
			objmap.put("itemName", "hardware");
			ObjItem hardwareItem = objDao.selectObjItemByItemName(objmap);
			if(hardwareItem!=null){
				hardwareList = objDao.selectCnValue(hardwareItem.getItemId());
			}
			objmap.put("itemName", "task");
			ObjItem taskItem = objDao.selectObjItemByItemName(objmap);
			if(taskItem!=null){
				taskList = objDao.selectCnValue(taskItem.getItemId());
			}
			
			objmap.put("itemType", "pid");
			List<Pid> pidList = getPid(objmap);
			listMap.put("basic", basicList);
			listMap.put("hardware", hardwareList);
			listMap.put("task", taskList);
			listMap.put("pid", pidList);
		//对数据结果进行包装传送
		result.setStatus(0);
		result.setMsg("主机监控信息加载成功");
		}else{
			result.setMsg("没有加载到该进程的指标");
		}
		
		result.setData(listMap);
		return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> addIndex(ReturnedValue value) {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//存放搜索参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", value.getHostId());
		//主机名称
		ObjectManagement obj = objDao.selectObjById(value.getHostId());
		//存放结果数据的集合
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//进程名称集合
		List<Pid> pidNameList = new ArrayList<Pid>();
		
		List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(value.getHostId());
		if(obj !=null){
			map.put("itemType", "pid");
			List<Pid> pidList = getPid(map);
			System.out.println(pidList);
			if(!pidList.isEmpty()){
//				for(Pid pid:pidList){
//					pidNameList.add(pid.getPidName());
//				}
				pidNameList.addAll(pidList);
				result.setStatus(0);
				result.setMsg("进程名称获取成功");
					
			}else{
				result.setMsg("没有获取到进程或所有进程监控都已添加");
			}
		}else{
			result.setMsg("没有监控中的主机");
		}
		resultMap.put("pidnames", pidNameList);
		resultMap.put("alarmusers", alarmUserList);
		result.setData(resultMap);
		return result;
	}
	@Override
	public MonitoringResult<Pid> save(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Pid> result = new MonitoringResult<Pid>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("itemName", value.getPidName());
		try {
			if(value.getAlarmRecUser()!=null){
					JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
					//保存指标信息
					ObjItem item = objDao.selectObjItemByItemName(map);
					item.setRemark(value.getRemark());
					objDao.updateItem(item);
					List<ObjItemProperty> objItemProList = objDao.getIndexName(item.getItemId());
					for(ObjItemProperty objItemProperty:objItemProList){
						objItemProperty.setQuantity(StringUtils.strToDouble(value.getQuantity()));
						objDao.updateIndex(objItemProperty);
						//保存告警信息
						Trigger trigger = new Trigger();
						String triggerId = StringUtils.uuid();
						trigger.setTriggerId(triggerId);
						trigger.setItemId(item.getItemId());
						trigger.setKeyId(objItemProperty.getKeyId());
						trigger.setUpperLimit(StringUtils.strToDouble(value.getUpperLimit()));
						trigger.setLowerLimit(StringUtils.strToDouble(value.getLowerLimit()));
						trigger.setAlarmLevel(StringUtils.strToInteger(value.getAlarmLevel()));
						objDao.saveAlarm(trigger);
						//保存告警接受人
						for(int j = 0;j<alarmja.size();j++){
							JSONObject alarmjb = alarmja.getJSONObject(j);
							AlarmReceiveUser user = new AlarmReceiveUser();
							user.setRceId(alarmjb.getString("rceId"));
							user.setPhone(alarmjb.getString("phone"));
							user.setEmail(alarmjb.getString("email"));
							user.setUserType(alarmjb.getString("userType"));
							user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
							
							user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
							
							user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
							
							objDao.updateUser(user);
						}
					}
					result.setStatus(0);
					result.setMsg("保存成功");
					return result;
				}else{
					result.setMsg("监控指标或接收人不能为空,保存失败");
				}
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("保存失败");
		}
		return result;
	}


}
